ActiveAdmin.register Fluctuation do

  permit_params :code, :name, :title, :href, :id_value, :trend

  scope :all, default: true
  scope :surge
  scope :surge_stop
  scope :plunge
  scope :plunge_stop

  index do
    selectable_column
    column :code do |fluctuation|
      stock = Stock.find_by(symbol: fluctuation.code)
      link_to fluctuation.code, admin_stock_path(stock.id), target: '_blank', rel: "noopener noreferrer" if stock
    end
    column :name
    column :title do |fluctuation|
      fluctuation.title.split("：")[1]
    end
    column :trend
    column :href do |fluctuation|
      link_to "详情", fluctuation.href, target: '_blank', rel: "noopener noreferrer"
    end
    column :created_at do |fluctuation|
      fluctuation.created_at.strftime("%Y-%m-%d %H:%M")
    end
  end

  sidebar '高频词' do
    fluctuations = Fluctuation.send(params[:scope] || "all")
    title_keys = fluctuations.map {|x| x.title.split("：")[1]&.split("+")}.flatten.compact.tally.sort_by { |k, v| v }.to_h
    keys_arr = title_keys.keys.reverse.first(50)
    values_arr = title_keys.values.reverse.first(50)

    div id: 'frequency', style: "width: 100%; height: 2000px;"
    script <<~JS.html_safe
      var frequency_Dom = document.getElementById('frequency');
      var frequency_Chart = echarts.init(frequency_Dom);
      var option = {
        title: {
          text: '舆情分析'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {},
        xAxis: {
          type: 'value',
          boundaryGap: [0, 1]
        },
        yAxis: {
          type: 'category',
          data: #{raw keys_arr}
        },
        series: [
          {
            name: 'title',
            type: 'bar',
            data: #{raw values_arr}
          }
        ]
      };
      option && frequency_Chart.setOption(option);
    JS
  end

  config.per_page = 100
end
